package com.sjr.easy.chat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.sjr.easy.chat.model.ChatGroup;
import com.sjr.easy.chat.model.ChatGroupUser;
import com.sjr.easy.chat.repo.ChatGroupRepo;
import com.sjr.easy.chat.service.ChatGroupService;
import com.sjr.easy.chat.service.ChatGroupUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@Transactional
public class ChatGroupServiceImpl implements ChatGroupService {

    @Autowired
    private ChatGroupUserService chatGroupUserService;

    @Autowired
    private ChatGroupRepo chatGroupRepo;

    @Override
    public ChatGroup createChatGroup(String chatGroupName, Long chatGroupCode, Long managerUserId, Set<Long> userIdSet) {
        log.info("chatGroupName:{}, managerUserId:{}, userIdSet:{}", chatGroupName, managerUserId, userIdSet);
        ChatGroup chatGroup = new ChatGroup();
        chatGroup.setCode(chatGroupCode);
        chatGroup.setName(chatGroupName);
        chatGroup.setManagerUserId(managerUserId);
        chatGroup.setCreateTime(new Date());

        chatGroupRepo.save(chatGroup);

        List<ChatGroupUser> chatGroupUserList = Lists.newArrayList();
        for (Long userId : userIdSet) {
            ChatGroupUser chatGroupUser = new ChatGroupUser();
            chatGroupUser.setChatGroupId(chatGroup.getId());
            chatGroupUser.setUserId(userId);
            chatGroupUser.setCreateTime(new Date());
            chatGroupUserList.add(chatGroupUser);
        }
        ChatGroupUser chatGroupUser = new ChatGroupUser();
        chatGroupUser.setChatGroupId(chatGroup.getId());
        chatGroupUser.setUserId(managerUserId);
        chatGroupUser.setCreateTime(new Date());
        chatGroupUserList.add(chatGroupUser);

        chatGroupUserService.batchAddChatGroupUser(chatGroupUserList);

        return chatGroup;
    }

    @Override
    public ChatGroup selectById(Long id) {
        log.info("id:{}", id);
        return chatGroupRepo.getById(id);
    }

    @Override
    public List<ChatGroup> getChatGroupByIdList(List<Long> chatGroupIdList) {
        log.info("chatGroupIdList:{}", JSON.toJSONString(chatGroupIdList));
        if (CollectionUtils.isEmpty(chatGroupIdList)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<ChatGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ChatGroup::getId, chatGroupIdList);
        return chatGroupRepo.list(queryWrapper);
    }
}
